package upload

import (
	"dcs/db"
	"dcs/model"
	"fmt"
	"time"

	"github.com/aliyun/aliyun-tablestore-go-sdk/tablestore"
)

var (
	endpoint                       = "https://wsctablestore.cn-shenzhen.ots.aliyuncs.com"
	accessKey                      = "LTAI4G1yvWe6pvnEjYq7xt8N"
	secretKey                      = "et3A0Ycy0SF7gxnft059uf6rnRtZZM"
	instance                       = "wsctablestore"
	Interval_upload_machine_status time.Duration
)

func init() {
	Interval_upload_machine_status = 3
}

func Push2tablestore() {

	defer func() {
		err := recover()
		if err != nil {
			fmt.Println(err)
		}
	}()

	select_str := "tid, machine_ip, status, spin_length, theory_length, actual_length, broken_boot, broken_total, prestart, run_state" +
		"cast(dtime as char) as dtime,average_speed, temperature, humidity, progress, front_speed, spindles"

	// tablestore 允许 一次最多写入 200 行
	handler := db.GormDb.Table("log_machine_status").Select(select_str).Where("uploaded=0").Order("tid").Limit(200)
	rows, err := handler.Rows()
	if err != nil {
		panic(err)
	}

	client := tablestore.NewClient(endpoint, instance, accessKey, secretKey)
	batchWriteReq := &tablestore.BatchWriteRowRequest{}

	row_count := 0
	var machine model.Log_machine_status
	var mids []int
	for rows.Next() {

		// rows.Scan(&machine) 错误用法
		db.GormDb.ScanRows(rows, &machine)

		putRowChange := new(tablestore.PutRowChange)
		putRowChange.TableName = Factory_no

		// 整形值 必须转换为 int64 才能上传成功
		putPk := new(tablestore.PrimaryKey)
		putPk.AddPrimaryKeyColumn("id", int64(machine.Tid))
		putRowChange.PrimaryKey = putPk

		putRowChange.AddColumn("ip", machine.Machine_ip)
		putRowChange.AddColumn("status", int64(machine.Status))
		putRowChange.AddColumn("spin_len", int64(machine.Spin_length))
		putRowChange.AddColumn("theory_len", int64(machine.Theory_length))
		putRowChange.AddColumn("actual_len", int64(machine.Actual_length))
		putRowChange.AddColumn("dtime", machine.Dtime)
		putRowChange.AddColumn("avg_speed", int64(machine.Average_speed))
		putRowChange.AddColumn("progress", int64(machine.Progress))
		putRowChange.AddColumn("front_speed", int64(machine.Front_speed))
		putRowChange.AddColumn("broken_boot", int64(machine.Broken_boot))
		putRowChange.AddColumn("broken_total", int64(machine.Broken_total))
		putRowChange.AddColumn("prestart", int64(machine.Prestart))
		putRowChange.AddColumn("run_state", int64(machine.Run_state))
		putRowChange.AddColumn("spindles", machine.Spindles)

		putRowChange.SetCondition(tablestore.RowExistenceExpectation_IGNORE)

		batchWriteReq.AddRowChange(putRowChange)
		row_count += 1
		mids = append(mids, machine.Tid)
	}

	if row_count < 1 {
		fmt.Println("No data to push")
		time.Sleep(time.Second)
		return
	}

	response, err := client.BatchWriteRow(batchWriteReq)

	if err != nil {
		fmt.Println("batch request failed with:", response)
	} else {
		// TO-DO 写入 uploaded=1,
		var updateData UpdateFields
		updateData.Uploaded = 1
		updateData.Upload_time = time.Now().Format("2006-01-02 15:04:05")
		handler.Updates(&updateData)

		fmt.Println("batch write row finished")
	}

	time.Sleep(time.Second)
}

func Cron_upload_machine_status() {

	for {
		Push2tablestore()
		time.Sleep(time.Second * Interval_upload_machine_status)
	}

}
